package org.smart4j.framework.helper;

import org.smart4j.framework.annotation.Action;
import org.smart4j.framework.bean.Handle;
import org.smart4j.framework.bean.Request;
import org.smart4j.framework.utils.ArrayUtil;
import org.smart4j.framework.utils.CollectionUtil;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * 控制器助手类
 *   描述：
 *      1.通过classHelpe获取所有定义了Controller注解的类
 *      2.通过反射获取该类中所有定义了Action注解方法的（简称action方法）
 *      3.根据Action注解获取请求路径与请求方法，封装一个请求对象与处理对象
 *      4.可根据请求方法与请求路径获取处理对象的方法
 * @Description:
 * @Author: Administrator
 * @Date: 2017/8/15 0015 下午 9:12
 */
public class ControllerHelper {

    private static final Map<Request, Handle> ACTION_MAP = new HashMap<>();

    static {
        Set<Class<?>> controllerClassSet = ClassHelper.getControllerClassSet();
        if (CollectionUtil.isNotEmpty(controllerClassSet)) {
            for (Class<?> controllerClass : controllerClassSet) {
                Method[] controllerMethods = controllerClass.getDeclaredMethods();
                if (ArrayUtil.isNotEmpty(controllerMethods)) {
                    for (Method controllerMethod : controllerMethods) {
                        if (controllerMethod.isAnnotationPresent(Action.class)) {
                            Action action= controllerMethod.getAnnotation(Action.class);
                            String mapping = action.value();
                            /*判断请求映射正则表达式（任意数字字母（大于<1）:+任意数字字母（大于1））*/
                            if (mapping.matches("\\w+:/\\w+")) {
                                String[] array = mapping.split(":");
                                if (ArrayUtil.isNotEmpty(array) && array.length == 2) {
                                    String requestMethod = array[0];
                                    String requestPath = array[1];
                                    Request request = new Request(requestMethod, requestPath);
                                    Handle handle = new Handle(controllerClass, controllerMethod);
                                    /*将reqeust对象、handler对象封装到Action_Map中*/
                                    ACTION_MAP.put(request, handle);
                                }
                             }
                        }
                    }
                }
             }
        }
    }

    /**
     * 通过请求方法与请求路径获取处理对象的方法
     * @param requestMethod
     * @param requestPath
     * @return
     */
    public static Handle getHandler(String requestMethod,String requestPath) {
        Request request = new Request(requestMethod, requestPath);
        return ACTION_MAP.get(request);
    }
}
